package com.episode.duetapi.logger;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Configuration
@Aspect
public class LogRecordAspect {
	
	private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);
	
	@Pointcut(value = "execution(public * com.episode..*.controller..*.*(..))")
	public void excudeService() {
		
	}
	
	@Around("excudeService()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		
		String url = request.getRequestURL().toString();
		String method = request.getMethod();
		String uri = request.getRequestURI();
		String queryString = request.getQueryString();
		Object[] args = pjp.getArgs();
		//List<Object> logArgs = StreamUtil.streamOf(args) .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse))) .collect(Collectors.toList());
		String[] parameters = ((CodeSignature) pjp.getStaticPart().getSignature()).getParameterNames();
		String params = "";
		
		//获取请求参数集合进行遍历拼接
		if(args.length>0) {
			if("POST".equals(method)) {
				Map map = getKeyAndValue(args,parameters);
				params = JSON.toJSONString(map);
			}else if("GET".equals(method)) {
				params = queryString;
			}
		}
		
		logger.info("请求开始=====>请求地址："+url);
		logger.info("请求开始=====>请求类型："+method);
		logger.info("请求开始=====>参数："+params);
		
		//result的值就是被拦截方法的返回值
		Object result = pjp.proceed();
		logger.info("请求结束======返回值是："+JSON.toJSONString(result));		
		return result;
		
	}
	
	public static Map<String,Object> getKeyAndValue(Object[] args,String[] params){
		Map<String,Object> map = new LinkedHashMap<>();
		for(int i=0;i<args.length;i++) {
			map.put(params[i], args[i]);//设置键值
		}
		return map;
	}

}
